<template>
<div>
    <!-- 验证码，localStorage 存储 时间，跳转页面，刷新不变 -->
    <button type="button" @click="GetCode" :disabled="!BtnStatus">
        {{BtnStatus?'获取验证码':`${countDownTime}秒后获取`}}
    </button>
</div>
</template>
<script>
export default {
    name: "countDown3",
    data() {
        return {
            BtnStatus: true,
            countDownTime: 60
        }
    },
    created () {
        let myEndTime= this.GetItem('myEndTime')
        myEndTime && this.codeCountDown(myEndTime)
    },
    methods: {
        GetItem(k) {
            return window.localStorage.getItem(k)||''
        },
        SetItem(k, con) {
            window.localStorage.setItem(k, con)
        },
        RemoveItem(k) {
            window.localStorage.removeItem(k)
        },
        // 点击按钮，出发事件，倒计时
        GetCode () {
            let endMsRes = (new Date()).getTime() + 60000;
            //SetItem 为封装 localStorage 方法
            this.SetItem('myEndTime', JSON.stringify(endMsRes));
            this.codeCountDown(endMsRes)
        },
        // 倒计时
        codeCountDown (endMsRes) {
            this.BtnStatus = false;
            this.countDownTime= Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
            let time = setTimeout(() => {
                this.countDownTime--
                if (this.countDownTime< 1) {
                    this.BtnStatus = true
                    this.countDownTime= 60
                    this.RemoveItem('myEndTime')
                    clearTimeout(time)
                } else {
                    this.codeCountDown(endMsRes)
                }
            }, 1000)
        }
    }
}
</script>